import { defineStore } from 'pinia';
import { GameEngine } from '../game/GameEngine.js';
import { Player } from '../game/Player.js';
import { Card } from '../game/Card.js';
import { audioManager } from '../utils/AudioManager.js';
import { useMultiplayerStore } from './multiplayer.js';

// AI配置管理
const AI_CONFIG = {
  // 出牌延迟配置
  delays: {
    aiThinking: 1500,        // AI思考时间
    turnCheck: 100,          // 回合检查延迟
    stateSync: 500,          // 状态同步延迟
    errorRetry: 3000,        // 错误重试延迟
    multiplayerInit: 500     // 多人游戏初始化延迟
  },
  
  // 超时配置
  timeouts: {
    aiDecision: 10000,       // AI决策超时(10秒)
    websocketOperation: 15000, // WebSocket操作超时
    connectionHealth: 5000   // 连接健康检查超时
  },
  
  // 重试配置
  retries: {
    maxAttempts: 3,          // 最大重试次数
    baseDelay: 500,          // 基础延迟
    maxDelay: 5000,          // 最大延迟
    exponentialBackoff: true  // 指数退避
  },
  
  // 性能监控
  monitoring: {
    enablePerformanceTracking: true,
    memoryCheckInterval: 30000,  // 内存检查间隔(30秒)
    performanceLogThreshold: 1000 // 性能日志阈值(1秒)
  }
};

export const useGameStore = defineStore('game', {
  state: () => ({
    gameEngine: null,
    currentPlayer: null,
    players: [],
    selectedCards: [],
    gameStatus: 'menu', // menu, loading, playing, finished
    gameMode: 'single', // single, multiplayer
    gameResult: null,
    message: '',
    messageType: 'info', // info, success, error
    roundInfo: {
      round: 1,
      currentTurn: 0,
      lastWinner: null
    },
    playHistory: [], // 出牌历史记录
    currentRoundHistory: [], // 当前轮次历史
    collectCountdown: 0, // 收牌倒计时
    countdownTimer: null, // 倒计时定时器
    showingRoundResult: false, // 是否正在显示轮次结果
    roundResultTimer: null, // 轮次结果显示定时器
    
    // AI性能监控和超时保护
    aiOperationTimers: new Map(), // AI操作定时器集合
    performanceMetrics: {
      aiDecisionTimes: [],
      lastGCTime: Date.now(),
      operationCount: 0
    },
    
    // 健壮性增强
    aiTimeoutProtection: {
      enabled: true,
      activeTimeout: null,
      fallbackCount: 0
    },

    // 无相相关状态
    showWuxiangDialog: false, // 显示无相弹窗
    wuxiangPlayer: null, // 无相玩家
    wuxiangCountdown: 5, // 无相倒计时
    wuxiangTimer: null, // 无相倒计时定时器

    // 扣了相关状态
    showKouLeDialog: false, // 显示扣了决策弹窗
    kouLeInitiator: null, // 发起扣了的玩家
    kouLeCountdown: 10, // 扣了决策倒计时
    kouLeTimer: null, // 扣了倒计时定时器
    kouLeDecisions: {}, // 玩家的扣了决策
    isKouLeActive: false // 是否处于扣了决策中
  }),

  getters: {
    // 获取其他玩家
    otherPlayers: (state) => {
      if (!state.currentPlayer) return [];
      return state.players.filter(p => p.id !== state.currentPlayer.id);
    },

    // 是否轮到当前玩家
    isMyTurn: (state) => {
      if (!state.gameEngine || !state.currentPlayer) return false;
      const currentTurnPlayer = state.gameEngine.getCurrentPlayer();
      return currentTurnPlayer && currentTurnPlayer.id === state.currentPlayer.id;
    },

    // 能否出牌
    canPlay: (state) => {
      if (!state.isMyTurn || state.selectedCards.length === 0) return false;

      // 检查是否处于扣牌模式
      const isPassingMode = state.canPass && state.gameEngine && state.gameEngine.roundCards.length > 0;
      const requiredCount = isPassingMode ? state.gameEngine.roundCards[0].cards.length : 0;

      if (isPassingMode && requiredCount > 1) {
        // 扣牌模式下，数量必须匹配
        if (state.selectedCards.length !== requiredCount) return false;
        // 验证是否是有效的出牌组合（用于压牌）
        const result = state.gameEngine.validatePlay(state.currentPlayer.id, state.selectedCards);
        return result.valid;
      }

      // 普通出牌模式
      return true;
    },

    // 能否扣牌
    canPass: (state) => {
      return state.isMyTurn && state.gameEngine && state.gameEngine.roundCards.length > 0;
    },

    // 本轮已出的牌
    roundCards: (state) => {
      if (!state.gameEngine) return [];
      return state.gameEngine.roundCards;
    },

    // 收牌统计
    collectedStats: (state) => {
      if (!state.gameEngine) return {};
      return state.gameEngine.collectedCards;
    },

    // 是否等待收牌（只有在显示结果阶段结束后才显示收牌弹框）
    waitingForCollection: (state) => {
      return state.gameEngine?.waitingForCollection && !state.showingRoundResult;
    },

    // 本轮赢家
    roundWinner: (state) => {
      const winnerFromEngine = state.gameEngine?.roundWinner;
      if (!winnerFromEngine) return null;
      // 返回store中的player对象，确保名字是最新的
      return state.players.find(p => p.id === winnerFromEngine.id) || winnerFromEngine;
    },

    // 首发玩家信息（用于UI显示）
    firstPlayerInfo: (state) => {
      if (!state.gameEngine?.firstPlayer) return null;
      const firstPlayer = state.gameEngine.firstPlayer;
      // 返回store中的player对象，确保名字是最新的
      const storePlayer = state.players.find(p => p.id === firstPlayer.id);
      return {
        player: storePlayer || firstPlayer,
        isFirstRound: state.gameEngine.isFirstRound
      };
    },

    // 是否可以发起扣了
    canInitiateKouLe: (state) => {
      if (!state.gameEngine) return false;
      // 真人玩家只要轮到自己出牌就可以发起扣了，不限制是否首出
      return state.isMyTurn && !state.isKouLeActive && !state.waitingForCollection;
    },

    // 获取扣了状态信息
    kouLeStatus: (state) => {
      if (!state.gameEngine) return null;
      return state.gameEngine.kouLeStatus;
    },

    // 获取等待决策的玩家
    waitingKouLeDecisions: (state) => {
      if (!state.isKouLeActive || !state.gameEngine) return [];
      const allPlayerIds = state.players.map(p => p.id);
      const decidedIds = Object.keys(state.gameEngine.kouLeStatus.decisions);
      return allPlayerIds.filter(id => !decidedIds.includes(id));
    }
  },

  actions: {
    // 设置游戏状态
    setGameStatus(status) {
      this.gameStatus = status;
    },

    // 设置游戏模式
    setGameMode(mode) {
      this.gameMode = mode;
    },

    // 获取两个不同的随机AI玩家名字
    getRandomAINames() {
      const names = [
        // 经典常见名字
        '张伟', '王芳', '李娜', '刘洋', '陈静', '杨明', '赵丽', '孙强',
        '周敏', '吴涛', '郑华', '王磊', '李静', '张敏', '刘伟', '陈涛',
        // 山西特色名字
        '高建国', '李建华', '王建军', '张建民', '刘建设', '赵建平',
        '马建新', '杨建中', '孙建良', '郭建东', '黄建西', '朱建南',
        // 有地方特色的名字
        '石大锤', '铁柱子', '金满仓', '银锁子', '田富贵', '山小虎',
        '河小龙', '柳春花', '桃二妮', '杏三娃', '槐老四', '榆五爷',
        // 亲切的名字
        '小王', '老李', '大张', '二刘', '三赵', '四孙', '五周', '六吴'
      ];

      // 随机选择两个不同的名字
      const shuffled = [...names].sort(() => Math.random() - 0.5);
      return [shuffled[0], shuffled[1]];
    },

    // 初始化游戏
    async initGame() {
      // 如果已经是加载状态，就不重复设置
      if (this.gameStatus !== 'loading') {
        this.gameStatus = 'loading';
      }

      this.message = '游戏准备中...';
      this.messageType = 'info';


      // 初始化音频系统（需要用户交互）
      try {
        await audioManager.init();
      } catch (error) {
        console.warn('音频初始化失败:', error);
      }

      // 异步处理游戏初始化
      await new Promise(resolve => setTimeout(resolve, 100)); // 确保UI更新

      try {
        // 创建玩家
        const humanPlayer = new Player('human', '你', false, '😊');

        const aiNames = this.getRandomAINames();
        const ai1 = new Player('ai1', aiNames[0], true, '🤖');
        const ai2 = new Player('ai2', aiNames[1], true, '🎮');

        // 顺时针顺序：人类（中间）→ AI玩家1（右边）→ AI玩家2（左边）
        this.players = [humanPlayer, ai1, ai2];
        this.currentPlayer = humanPlayer;

        // 模拟加载进度
        await this.simulateLoadingSteps();

        // 创建游戏引擎
        this.gameEngine = new GameEngine();
        const initResult = await this.gameEngine.initGameAsync(this.players);

        // 检查是否需要重新发牌（无相情况）
        if (initResult.needRedeal) {
          await this.handleWuxiang(initResult.wuxiangPlayer);
          return; // 等待重新发牌
        }

        this.selectedCards = [];
        this.playHistory = []; // 清空历史记录
        this.currentRoundHistory = []; // 清空当前轮次历史

        // 更新回合信息
        this.updateRoundInfo();

        // 确保所有数据完全准备好后再设置playing状态
        await new Promise(resolve => setTimeout(resolve, 200));

        // 设置游戏状态为进行中
        this.gameStatus = 'playing';

        // 根据当前玩家设置提示信息，增加首发玩家提示
        const currentPlayer = this.gameEngine.getCurrentPlayer();
        const firstPlayerName = this.gameEngine.firstPlayer?.name || '未知';

        if (currentPlayer && currentPlayer.id === this.currentPlayer.id) {
          this.message = `🎲 随机选择：${firstPlayerName}首出！游戏开始，轮到你出牌。`;
          this.messageType = 'info';
          // 语音播报
          audioManager.speak(`随机选择${firstPlayerName}首出，游戏开始，轮到你出牌`);
        } else {
          this.message = `🎲 随机选择：${firstPlayerName}首出！游戏开始，${currentPlayer.name}先出牌。`;
          this.messageType = 'info';
          // 语音播报
          audioManager.speak(`随机选择${firstPlayerName}首出，游戏开始，${currentPlayer.name}先出牌`);
        }

        // 开始背景音乐（如果用户已开启）
        if (audioManager.isMusicEnabled) {
          audioManager.startBackgroundMusic();
        }

        // 延迟检查AI回合，确保界面完全渲染
        setTimeout(() => {
          this.checkAITurn();
        }, 100);

      } catch (error) {
        console.error('游戏初始化失败:', error);
        this.message = '游戏初始化失败，请重试';
        this.messageType = 'error';
        this.gameStatus = 'menu';
      }
    },

    // 处理无相情况
    async handleWuxiang(wuxiangPlayer) {
      this.wuxiangPlayer = wuxiangPlayer;
      this.showWuxiangDialog = true;
      this.wuxiangCountdown = 5;

      // 播放洗牌音效
      try {
        audioManager.playShuffleSound();
      } catch (error) {
        console.warn('洗牌音效播放失败:', error);
      }

      // 开始倒计时
      this.startWuxiangCountdown();
    },

    // 开始无相倒计时
    startWuxiangCountdown() {
      if (this.wuxiangTimer) {
        clearInterval(this.wuxiangTimer);
      }

      this.wuxiangTimer = setInterval(() => {
        this.wuxiangCountdown--;
        if (this.wuxiangCountdown <= 0) {
          this.closeWuxiangDialog();
        }
      }, 1000);
    },

    // 关闭无相弹窗并重新发牌
    async closeWuxiangDialog() {
      if (this.wuxiangTimer) {
        clearInterval(this.wuxiangTimer);
        this.wuxiangTimer = null;
      }

      this.showWuxiangDialog = false;
      this.wuxiangPlayer = null;

      // 重新发牌
      await this.redealCards();
    },

    // 重新发牌
    async redealCards() {
      this.message = '重新发牌中...';

      // 重新初始化游戏引擎
      const initResult = await this.gameEngine.initGameAsync(this.players);

      // 再次检查无相（理论上很少出现连续无相）
      if (initResult.needRedeal) {
        await this.handleWuxiang(initResult.wuxiangPlayer);
        return;
      }

      // 继续正常游戏流程
      this.selectedCards = [];
      this.playHistory = [];
      this.currentRoundHistory = [];
      this.updateRoundInfo();

      await new Promise(resolve => setTimeout(resolve, 200));

      this.gameStatus = 'playing';

      // 根据当前玩家设置提示信息，重新发牌也显示首发提示
      const currentPlayer = this.gameEngine.getCurrentPlayer();
      const firstPlayerName = this.gameEngine.firstPlayer?.name || '未知';

      if (currentPlayer && currentPlayer.id === this.currentPlayer.id) {
        this.message = `🎲 重新随机选择：${firstPlayerName}首出！重新发牌完成，轮到你出牌。`;
        this.messageType = 'info';
        // 语音播报
        audioManager.speak(`重新随机选择${firstPlayerName}首出，重新发牌完成，轮到你出牌`);
      } else {
        this.message = `🎲 重新随机选择：${firstPlayerName}首出！重新发牌完成，${currentPlayer.name}先出牌。`;
        this.messageType = 'info';
        // 语音播报
        audioManager.speak(`重新随机选择${firstPlayerName}首出，重新发牌完成，${currentPlayer.name}先出牌`);
      }

      if (audioManager.isMusicEnabled) {
        audioManager.startBackgroundMusic();
      }

      setTimeout(() => {
        this.checkAITurn();
      }, 100);
    },

    // 模拟加载步骤
    async simulateLoadingSteps() {
      const steps = [
        { delay: 300, message: '创建玩家...' },
        { delay: 400, message: '准备牌组...' },
        { delay: 500, message: '洗牌中...' }, // 移除音效，已在按钮点击时播放
        { delay: 400, message: '分发手牌...' },
        { delay: 300, message: '初始化AI策略...' },
        { delay: 200, message: '准备就绪...' }
      ];

      for (const step of steps) {
        this.message = step.message;
        await new Promise(resolve => setTimeout(resolve, step.delay));
      }
    },

    // 选择/取消选择牌
    toggleCardSelection(card) {
      const index = this.selectedCards.findIndex(c => c.id === card.id);

      if (index !== -1) {
        // 取消选择
        this.selectedCards.splice(index, 1);
        this.selectedCards = [...this.selectedCards];
      } else {
        // 选择牌
        if (this.selectedCards.length === 0) {
          // 第一张牌，直接选择
          this.selectedCards = [card];
        } else {
          // 检查当前是否处于扣牌状态（以是否已有出牌为准）
          const isPassingMode = this.gameEngine &&
            Array.isArray(this.gameEngine.roundCards) &&
            this.gameEngine.roundCards.length > 0 &&
            !this.gameEngine.waitingForCollection;
          const requiredCount = isPassingMode
            ? Math.max(this.gameEngine.roundCards[0]?.cards?.length || 0, 1)
            : 0;

          // 调试日志
          if (isPassingMode) {
            console.log('[选牌调试] 扣牌模式:', {
              requiredCount,
              currentSelected: this.selectedCards.length,
              roundCards: this.gameEngine.roundCards
            });
          }

          if (isPassingMode && requiredCount > 1) {
            // 扣牌模式：允许选择任意牌，直到达到所需数量
            if (this.selectedCards.length < requiredCount) {
              this.selectedCards = [...this.selectedCards, card];
              console.log(`[选牌调试] 添加牌，当前已选${this.selectedCards.length}/${requiredCount}张`);
            } else {
              // 已达到所需数量，清空之前的选择，重新选择当前牌
              this.selectedCards = [card];
              console.log('[选牌调试] 已达到所需数量，清空重新选择');
            }
          } else {
            // 出牌模式：检查是否可以和已选择的牌组合
            let canCombine = false;

            // 检查是否都是曲曲牌
            const ququRanks = ['J', 'Q', 'K'];
            const allSelectedAreQuqu = this.selectedCards.every(c => ququRanks.includes(c.rank));
            const currentIsQuqu = ququRanks.includes(card.rank);

            if (allSelectedAreQuqu && currentIsQuqu) {
              // 都是曲曲牌，检查颜色是否一致
              const redSuits = ['hearts', 'diamonds'];
              const firstCardIsRed = redSuits.includes(this.selectedCards[0].suit);
              const currentCardIsRed = redSuits.includes(card.suit);
              canCombine = firstCardIsRed === currentCardIsRed;
            } else if (this.selectedCards.length === 1) {
              // 只选了一张，检查是否能组成对子
              canCombine = this.selectedCards[0].canPairWith(card);
            }

            if (canCombine) {
              this.selectedCards = [...this.selectedCards, card];
            } else {
              // 不能组合，重新选择
              this.selectedCards = [card];
            }
          }
        }
      }
    },

    // 出牌
    playCards() {
      if (!this.canPlay) return;

      const result = this.gameEngine.playCards(this.currentPlayer.id, this.selectedCards);

      if (result.valid) {
        const playedCards = this.selectedCards.slice();
        this.selectedCards = [];
        this.message = `你出了${this.getCardsDescription(playedCards)}`;
        this.messageType = 'success';

        // 语音播报
        audioManager.speak(`你出了${this.getCardsDescriptionForSpeech(playedCards)}`);

        // 添加到当前轮次历史
        this.currentRoundHistory.push({
          player: this.currentPlayer.name,
          cards: playedCards,
          passed: false
        });

        // 更新回合信息
        this.updateRoundInfo();

        // 检查是否等待收牌
        if (this.gameEngine.waitingForCollection) {
          this.startCollectCountdown();
          return;
        }

        // 检查游戏是否结束
        if (this.gameEngine.gameStatus === 'finished') {
          this.endGame();
        } else {
          // AI回合
          setTimeout(() => this.checkAITurn(), 1000);
        }
      } else {
        this.message = result.message;
        this.messageType = 'error';
      }
    },

    // 扣牌
    pass() {
      if (!this.canPass) return;

      // 检查是否需要选牌扣牌
      const firstPlay = this.gameEngine.roundCards[0];
      const requiredCount = firstPlay.cards.length;

      // 如果需要扣多张牌但没有选中足够的牌，提示用户选牌
      if (requiredCount > 1 && this.selectedCards.length !== requiredCount) {
        this.message = `扣牌需要选中${requiredCount}张牌`;
        this.messageType = 'error';
        // 语音播报错误提示
        audioManager.speak(`扣牌需要选中${requiredCount}张牌`);
        return;
      }

      // 如果是单张扣牌且没有选牌，自动选择最小的牌
      let cardsToDiscard = [];
      if (requiredCount === 1) {
        if (this.selectedCards.length === 0) {
          // 自动选择最小的牌
          cardsToDiscard = [this.currentPlayer.cards[this.currentPlayer.cards.length - 1]];
        } else {
          cardsToDiscard = this.selectedCards.slice();
        }
      } else {
        // 多张扣牌，使用选中的牌
        cardsToDiscard = this.selectedCards.slice();
      }

      const result = this.gameEngine.pass(this.currentPlayer.id, cardsToDiscard);

      if (result.valid) {
        // GameEngine已经处理了牌的移除，这里不需要再移除
        this.selectedCards = [];
        this.message = `你扣了${cardsToDiscard.length}张牌`;
        this.messageType = 'info';

        // 语音播报
        audioManager.speak(`你扣了${cardsToDiscard.length}张牌`);

        // 添加到当前轮次历史
        this.currentRoundHistory.push({
          player: this.currentPlayer.name,
          cards: [],
          passed: true
        });

        // 更新回合信息
        this.updateRoundInfo();

        // 检查是否等待收牌
        if (this.gameEngine.waitingForCollection) {
          this.startCollectCountdown();
          return;
        }

        // AI回合
        setTimeout(() => this.checkAITurn(), 1000);
      } else {
        this.message = result.message;
        this.messageType = 'error';
        // 语音播报错误提示
        audioManager.speak(result.message);

        // 确保错误消息能被看到，延长显示时间
        setTimeout(() => {
          // 如果消息仍然是当前错误消息，则清空
          if (this.message === result.message && this.messageType === 'error') {
            this.message = '';
            this.messageType = 'info';
          }
        }, 4000); // 延长到4秒
      }
    },

    // 检查是否轮到AI出牌（统一处理单人和多人模式）
    checkAITurn() {
      if (this.gameStatus !== 'playing') return;
      
      // 根据游戏模式选择不同的处理方式
      if (this.gameMode === 'multiplayer') {
        this.checkMultiplayerAITurn();
      } else {
        this.checkSinglePlayerAITurn();
      }
    },

    // 单机模式AI出牌检查
    checkSinglePlayerAITurn() {
      if (this.gameEngine.gameStatus !== 'playing') return;

      // 如果在等待收牌，不继续
      if (this.gameEngine.waitingForCollection) {
        this.startCollectCountdown();
        return;
      }

      // 使用store中的players，而不是GameEngine中的
      const currentPlayerFromEngine = this.gameEngine.getCurrentPlayer();
      const currentPlayer = this.players.find(p => p.id === currentPlayerFromEngine?.id);

      if (currentPlayer && currentPlayer.isAI) {
        // AI思考时间
        setTimeout(() => {
          const result = this.gameEngine.makeAIMove(currentPlayer.id);

          if (result && result.valid) {
            // 获取最新的出牌信息
            const lastPlay = this.gameEngine.roundCards[this.gameEngine.roundCards.length - 1];
            if (lastPlay && lastPlay.passed) {
              this.message = `${currentPlayer.name} 选择了扣牌`;
              // 语音播报
              audioManager.speak(`${currentPlayer.name}扣牌`);
              // 添加到当前轮次历史
              this.currentRoundHistory.push({
                player: currentPlayer.name,
                cards: [],
                passed: true
              });
            } else if (lastPlay && lastPlay.cards.length > 0) {
              const cardsDesc = this.getCardsDescription(lastPlay.cards);
              const speechDesc = this.getCardsDescriptionForSpeech(lastPlay.cards);
              this.message = `${currentPlayer.name} 出了${cardsDesc}`;
              // 语音播报
              audioManager.speak(`${currentPlayer.name}出了${speechDesc}`);
              // 添加到当前轮次历史
              this.currentRoundHistory.push({
                player: currentPlayer.name,
                cards: lastPlay.cards,
                passed: false
              });
            }
            this.messageType = 'info';
          }

          // 更新回合信息
          this.updateRoundInfo();

          // 检查游戏是否结束
          if (this.gameEngine.gameStatus === 'finished') {
            this.endGame();
          } else {
            // 继续检查下一个玩家
            this.checkAITurn();
          }
        }, 1500);
      }
    },

    // 更新回合信息
    updateRoundInfo() {
      if (!this.gameEngine) return;

      this.roundInfo = {
        round: this.gameEngine.currentRound,
        currentTurn: this.gameEngine.currentPlayerIndex,
        lastWinner: this.gameEngine.lastRoundWinner
      };
    },

    // 获取牌的描述
    getCardsDescription(cards) {
      if (!cards || cards.length === 0) return '';

      if (cards.length === 1) {
        return `${cards[0].displayName}${cards[0].getSymbol()}`;
      } else if (cards.length === 2) {
        // 检查是否是大小王对
        if (cards.every(c => c.rank === 'joker') && cards[0].displayName !== cards[1].displayName) {
          return '大小王对';
        }
        return `一对${cards[0].displayName}`;
      } else {
        // 多张牌（曲曲）
        const cardName = cards[0].displayName;
        return `${cards.length}张${cardName}`;
      }
    },

    // 获取语音播报用的牌描述（单牌不包含花色符号）
    getCardsDescriptionForSpeech(cards) {
      if (!cards || cards.length === 0) return '';

      if (cards.length === 1) {
        // 单牌只报牌名，不报花色符号
        return cards[0].displayName;
      } else if (cards.length === 2) {
        // 检查是否是大小王对
        if (cards.every(c => c.rank === 'joker') && cards[0].displayName !== cards[1].displayName) {
          return '大小王对';
        }
        return `一对${cards[0].displayName}`;
      } else {
        // 多张牌（曲曲）
        const cardName = cards[0].displayName;
        return `${cards.length}张${cardName}`;
      }
    },

    // 结束游戏
    endGame() {
      const results = this.gameEngine.calculateGameResults();
      this.gameResult = results;
      this.gameStatus = 'finished';

      // 停止背景音乐
      audioManager.stopBackgroundMusic();

      // 判断玩家是否获胜
      const playerResult = results.results.find(r => r.player.id === this.currentPlayer?.id);
      if (playerResult && playerResult.level !== '不够') {
        audioManager.speak(`游戏结束，你获得了${playerResult.level}的成绩`);
      } else {
        audioManager.speak('游戏结束，很遗憾你没有达到要求');
      }

      // 更新星光币
      results.payments.forEach(payment => {
        const fromPlayer = this.players.find(p => p.id === payment.from);
        const toPlayer = this.players.find(p => p.id === payment.to);

        if (fromPlayer) {
          fromPlayer.updateStarCoins(-payment.amount);
        }
        if (toPlayer) {
          toPlayer.updateStarCoins(payment.amount);
        }
      });

      // 保存星光币到本地
      this.saveStarCoins();
    },

    // 保存星光币
    saveStarCoins() {
      if (this.currentPlayer) {
        localStorage.setItem('starCoins', this.currentPlayer.starCoins.toString());
      }
    },

    // 加载星光币
    loadStarCoins() {
      const saved = localStorage.getItem('starCoins');
      if (saved && this.currentPlayer) {
        this.currentPlayer.starCoins = parseInt(saved) || 100;
      }
    },

    // 返回菜单
    backToMenu() {
      this.gameStatus = 'menu';
      this.gameEngine = null;
      this.selectedCards = [];
      this.gameResult = null;

      // 停止背景音乐
      audioManager.stopBackgroundMusic();

      // 清理所有定时器和资源
      this.clearAllTimers();

      // 重置AI状态
      this.resetAIState();

      // 如果是多人模式，需要离开房间并断开连接
      if (this.gameMode === 'multiplayer') {
        const multiplayerStore = useMultiplayerStore();
        if (multiplayerStore) {
          // 离开房间
          multiplayerStore.leaveRoom().catch(err => {
            console.warn('离开房间失败:', err);
          });
          // 断开连接
          multiplayerStore.disconnect();
        }
        // 重置游戏模式为单机
        this.gameMode = 'single';
      }
    },

    // 再来一局
    playAgain() {
      this.gameResult = null;

      // 根据游戏模式区分处理
      if (this.gameMode === 'single') {
        // 单机模式：直接重新初始化游戏
        this.initGame();
      } else if (this.gameMode === 'multiplayer') {
        // 多人模式：返回菜单，让用户重新选择房间
        // 因为多人对战需要重新匹配玩家或加入房间
        this.backToMenu();
      }
    },

    // 开始收牌倒计时 - 优化为时序分离显示
    startCollectCountdown() {
      // 使用store中的玩家信息而不是GameEngine中的
      const winnerFromEngine = this.gameEngine.roundWinner;
      const winner = winnerFromEngine ? this.players.find(p => p.id === winnerFromEngine.id) : null;
      const winnerName = winner?.name || '无人';

      // 第一阶段：显示轮次结果预览（2.5秒）
      this.showingRoundResult = true;
      this.message = `轮次结束 - ${winnerName}获胜！`;
      this.messageType = 'info';

      // 语音播报
      if (winner?.id === this.currentPlayer?.id) {
        audioManager.speak(`你赢得本轮`);
      } else {
        audioManager.speak(`${winnerName}赢得本轮`);
      }

      // 清除之前的定时器
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }
      if (this.roundResultTimer) {
        clearTimeout(this.roundResultTimer);
      }

      // 2.5秒后进入收牌阶段
      this.roundResultTimer = setTimeout(() => {
        this.showingRoundResult = false;
        this.startActualCollectCountdown(winnerName);
      }, 2500);
    },

    // 实际的收牌倒计时
    startActualCollectCountdown(winnerName) {
      // 先清除旧的定时器（如果存在）
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
        this.countdownTimer = null;
      }

      this.collectCountdown = 3;
      this.message = `${winnerName}赢得本轮，3秒后自动收牌`;
      this.messageType = 'info';

      this.countdownTimer = setInterval(() => {
        this.collectCountdown--;
        console.log('[倒计时] collectCountdown =', this.collectCountdown, 'waitingForCollection =', this.gameEngine?.waitingForCollection);

        if (this.collectCountdown <= 0) {
          clearInterval(this.countdownTimer);
          this.countdownTimer = null;
          console.log('[倒计时] 倒计时结束，准备自动收牌');
          this.collectCards();
        }
      }, 1000);
    },

    // 收牌
    collectCards() {
      console.log('[收牌] collectCards 被调用，waitingForCollection =', this.gameEngine?.waitingForCollection);

      if (!this.gameEngine?.waitingForCollection) {
        console.warn('[收牌] 警告：不在等待收牌状态，取消收牌操作');
        // 即使不在等待收牌状态，也要清除定时器和倒计时显示
        this.collectCountdown = 0;
        if (this.countdownTimer) {
          clearInterval(this.countdownTimer);
          this.countdownTimer = null;
        }
        if (this.roundResultTimer) {
          clearTimeout(this.roundResultTimer);
          this.roundResultTimer = null;
        }
        this.showingRoundResult = false;
        return;
      }

      // 清除定时器
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
        this.countdownTimer = null;
      }
      if (this.roundResultTimer) {
        clearTimeout(this.roundResultTimer);
        this.roundResultTimer = null;
      }

      // 重置状态
      this.showingRoundResult = false;

      // 计算本轮收牌数 - 基于第一个出牌的数量
      const cardsPerPlayer = this.gameEngine.roundCards[0].cards.length;
      const actualCardsCount = cardsPerPlayer * 3;

      // 保存本轮历史到总历史
      this.playHistory.push({
        round: this.gameEngine.currentRound,
        plays: [...this.currentRoundHistory],
        winner: this.gameEngine.roundWinner?.name || '无人',
        collected: actualCardsCount,
        time: new Date().toLocaleTimeString()
      });

      // 清空当前轮次历史
      this.currentRoundHistory = [];

      this.collectCountdown = 0;

      // 区分单机模式和多人模式
      if (this.gameMode === 'single') {
        // 单机模式：调用 GameEngine 的 collectCards 方法
        console.log('[收牌] 单机模式：执行 gameEngine.collectCards()，收牌数 =', actualCardsCount);
        this.gameEngine.collectCards();
        console.log('[收牌] 收牌完成，waitingForCollection =', this.gameEngine.waitingForCollection);
      } else if (this.gameMode === 'multiplayer') {
        // 多人模式：通知服务器收牌
        console.log('[收牌] 多人模式：通知服务器收牌，收牌数 =', actualCardsCount);

        // 异步通知服务器收牌
        (async () => {
          try {
            const { useMultiplayerStore } = await import('./multiplayer.js');
            const multiplayerStore = useMultiplayerStore();

            console.log('[收牌] 发送收牌请求到服务器');
            const result = await multiplayerStore.collectCards();
            console.log('[收牌] 服务器收牌响应:', result);

            // 服务器会推送新的游戏状态，包括清除 waitingForCollection
            // 不需要在这里手动更新状态
          } catch (error) {
            console.error('[收牌] 通知服务器收牌失败:', error);

            // 如果通知服务器失败，手动清除本地状态避免UI卡住
            this.gameEngine.waitingForCollection = false;
            this.gameEngine.roundWinner = null;
            this.gameEngine.roundCards = [];
            this.message = '收牌失败: ' + error.message;
            this.messageType = 'error';
          }
        })();
      }

      // 更新回合信息
      this.updateRoundInfo();

      // 不需要手动清空消息，让自然的消息流程处理
      // this.message = ''; // 删除这行，避免显示空消息框

      // 检查游戏是否结束
      if (this.gameEngine.gameStatus === 'finished') {
        this.endGame();
      } else {
        // 单机模式：立即继续游戏
        // 多人模式：等待服务器推送新状态后，会自动触发 checkAITurn
        if (this.gameMode === 'single') {
          setTimeout(() => this.checkAITurn(), 500);
        } else {
          console.log('[收牌] 多人模式：等待服务器推送新的游戏状态');
        }
      }
    },

    // 发起扣了
    initiateKouLe() {
      /*if (!this.canInitiateKouLe) {
        this.message = '当前不能选择扣了';
        this.messageType = 'error';
        return;
      }*/

      const result = this.gameEngine.initiateKouLe(this.currentPlayer.id);

      if (result.valid) {
        this.isKouLeActive = true;
        this.kouLeInitiator = this.currentPlayer;
        this.kouLeDecisions = { [this.currentPlayer.id]: 'kou' };
        this.showKouLeDialog = true;
        this.kouLeCountdown = 10;

        this.message = `${this.currentPlayer.name}选择了扣了，等待其他玩家决策`;
        this.messageType = 'info';

        // 语音播报
        audioManager.speak(`${this.currentPlayer.name}选择了扣了，等待其他玩家决策`);

        // 开始倒计时
        this.startKouLeCountdown();

        // AI玩家自动决策
        setTimeout(() => this.makeAIKouLeDecisions(), 1500);
      } else {
        this.message = result.message;
        this.messageType = 'error';
      }
    },

    // 响应扣了决策
    respondToKouLe(decision) {
      if (!this.isKouLeActive || !this.gameEngine) return;

      const result = this.gameEngine.respondToKouLe(this.currentPlayer.id, decision);

      if (result.valid) {
        this.kouLeDecisions[this.currentPlayer.id] = decision;

        if (result.result) {
          // 所有人都已决策或有人选择了"宣"，立即处理结果
          this.handleKouLeResult(result);
        } else {
          // 等待其他玩家决策
          this.message = `你选择了${decision === 'kou' ? '扣了' : '宣'}，等待其他玩家决策`;
          this.messageType = 'info';
        }
      } else {
        this.message = result.message;
        this.messageType = 'error';
      }
    },

    // AI玩家做扣了决策
    makeAIKouLeDecisions() {
      if (!this.isKouLeActive || !this.gameEngine) return;

      // 获取需要决策的AI玩家
      const waitingPlayers = this.waitingKouLeDecisions;
      const aiPlayers = this.players.filter(p => p.isAI && waitingPlayers.includes(p.id));

      // 按顺序为AI玩家做决策
      let currentIndex = 0;

      const makeNextDecision = () => {
        if (currentIndex >= aiPlayers.length || !this.isKouLeActive) return;

        // 检查是否已经有人"宣"了
        if (this.gameEngine.kouLeStatus.xuanPlayers.length > 0) {
          console.log('已有玩家选择"宣"，停止AI决策');
          return;
        }

        const aiPlayer = aiPlayers[currentIndex];
        const decision = this.gameEngine.makeAIKouLeDecision(aiPlayer);
        const result = this.gameEngine.respondToKouLe(aiPlayer.id, decision);

        if (result.valid) {
          this.kouLeDecisions[aiPlayer.id] = decision;
          this.message = `${aiPlayer.name}选择了${decision === 'kou' ? '扣了' : '宣'}`;
          this.messageType = 'info';

          // 语音播报
          audioManager.speak(`${aiPlayer.name}选择了${decision === 'kou' ? '扣了' : '宣'}`);

          if (result.result) {
            // 决策已经结束（有人宣或全部决策完成）
            setTimeout(() => this.handleKouLeResult(result), 1000);
          } else {
            // 继续下一个AI的决策
            currentIndex++;
            setTimeout(makeNextDecision, 1500);
          }
        }
      };

      // 开始第一个AI的决策
      setTimeout(makeNextDecision, 1500);
    },

    // 处理扣了结果
    handleKouLeResult(result) {
      // 清除倒计时
      if (this.kouLeTimer) {
        clearInterval(this.kouLeTimer);
        this.kouLeTimer = null;
      }

      this.showKouLeDialog = false;
      this.isKouLeActive = false;

      if (result.result === 'redeal') {
        // 全部扣了，需要重新发牌
        this.message = result.message;
        this.messageType = 'info';

        // 语音播报
        audioManager.speak('所有人都选择扣了，即将重新发牌');

        // 3秒后重新发牌
        setTimeout(() => {
          this.redealForKouLe();
        }, 3000);
      } else if (result.result === 'continue') {
        // 有人宣，游戏继续
        this.message = result.message;
        this.messageType = 'info';

        // 语音播报
        audioManager.speak(result.message);

        // 清空扣了相关状态
        this.kouLeDecisions = {};
        this.kouLeInitiator = null;

        // 检查当前是否轮到AI
        setTimeout(() => this.checkAITurn(), 1000);
      }
    },

    // 扣了倒计时
    startKouLeCountdown() {
      if (this.kouLeTimer) {
        clearInterval(this.kouLeTimer);
      }

      this.kouLeTimer = setInterval(() => {
        this.kouLeCountdown--;
        if (this.kouLeCountdown <= 0) {
          // 时间到，未决策的玩家自动选择"扣了"
          this.autoCompleteKouLeDecisions();
        }
      }, 1000);
    },

    // 自动完成扣了决策
    autoCompleteKouLeDecisions() {
      if (!this.isKouLeActive || !this.gameEngine) return;

      const waitingPlayers = this.waitingKouLeDecisions;

      // 为未决策的玩家自动选择"扣了"
      waitingPlayers.forEach(playerId => {
        const result = this.gameEngine.respondToKouLe(playerId, 'kou');
        if (result.valid) {
          this.kouLeDecisions[playerId] = 'kou';

          const player = this.players.find(p => p.id === playerId);
          this.message = `${player.name}超时，自动选择了扣了`;
          this.messageType = 'info';
        }
      });

      // 检查是否所有人都已决策
      const finalResult = this.gameEngine.resolveKouLe();
      if (finalResult.valid) {
        this.handleKouLeResult(finalResult);
      }
    },

    // 因扣了重新发牌
    async redealForKouLe() {
      this.message = '重新发牌中...';
      this.messageType = 'info';

      // 保留原首出玩家
      const originalFirstPlayer = this.gameEngine.firstPlayer;

      // 重置收牌数量和扣了状态
      this.gameEngine.collectedCards = {};
      this.players.forEach(player => {
        this.gameEngine.collectedCards[player.id] = 0;
      });

      // 重置扣了状态
      this.gameEngine.kouLeStatus = {
        isActive: false,
        initiator: null,
        initiatorPlayer: null,
        decisions: {},
        xuanPlayers: [],
        riskMultiplier: 2
      };

      // 重置其他游戏状态
      this.gameEngine.roundCards = [];
      this.gameEngine.waitingForCollection = false;
      this.gameEngine.roundWinner = null;
      this.gameEngine.currentRound = 1;
      this.gameEngine.isFirstRound = true;

      // 重新发牌，但保持首出玩家不变
      await this.gameEngine.dealCardsAsync();

      // 检查无相情况
      const wuxiangResult = this.gameEngine.checkWuxiang();
      if (wuxiangResult.hasWuxiang) {
        await this.handleWuxiang(wuxiangResult.player);
        return;
      }

      // 恢复首出玩家
      this.gameEngine.firstPlayer = originalFirstPlayer;
      const firstPlayerIndex = this.players.findIndex(p => p.id === originalFirstPlayer.id);
      this.gameEngine.currentPlayerIndex = firstPlayerIndex;

      this.selectedCards = [];
      this.message = `重新发牌完成，${originalFirstPlayer.name}继续首出`;
      this.messageType = 'info';

      // 语音播报
      audioManager.speak(`重新发牌完成，${originalFirstPlayer.name}继续首出`);

      // 检查是否轮到AI
      setTimeout(() => this.checkAITurn(), 1000);
    },

    /**
     * 初始化多人游戏
     */
    async initMultiplayerGame(multiplayerGameState) {
      try {
        this.gameStatus = 'loading';
        this.gameMode = 'multiplayer';
        this.message = '多人游戏准备中...';
        this.messageType = 'info';

        // 数据结构预检查
        console.log('接收到的多人游戏状态:', multiplayerGameState);
        
        if (!multiplayerGameState) {
          throw new Error('多人游戏状态数据为空');
        }

        // 关键数据验证
        const requiredFields = ['players'];
        for (const field of requiredFields) {
          if (!(field in multiplayerGameState)) {
            throw new Error(`缺少必要字段: ${field}`);
          }
        }

        // 初始化音频系统
        try {
          await audioManager.init();
        } catch (error) {
          console.warn('音频初始化失败:', error);
        }

        // 模拟加载步骤（保持用户体验一致性）
        await this.simulateMultiplayerLoadingSteps();

        // 从多人游戏状态构建玩家对象
        this.players = this.createPlayersFromMultiplayerState(multiplayerGameState);

        // 先创建兼容的游戏引擎状态（包含 currentPlayerId）
        this.gameEngine = this.createMultiplayerGameEngine(multiplayerGameState);

        // 再确定当前客户端玩家对象，优先使用多人状态中的 currentPlayerId
        this.currentPlayer = this.players.find(p => p.id === multiplayerGameState.currentPlayerId) 
          || this.findCurrentPlayer();

        this.selectedCards = [];
        this.playHistory = [];
        this.currentRoundHistory = [];

        // 更新回合信息
        this.updateRoundInfo();

        // 设置游戏状态为进行中
        this.gameStatus = 'playing';

        // 设置当前回合提示
        this.setMultiplayerTurnMessage();

        // 开始背景音乐
        if (audioManager.isMusicEnabled) {
          audioManager.startBackgroundMusic();
        }

        console.log('多人游戏初始化完成');

        // 启动内存监控
        this.startMemoryMonitoring();
        
        // 延迟检查AI回合，确保WebSocket连接稳定
        setTimeout(() => {
          this.checkMultiplayerAITurn();
        }, AI_CONFIG.delays.multiplayerInit);
      } catch (error) {
        console.error('多人游戏初始化失败:', error);
        
        // 详细的错误处理和用户反馈
        let userMessage = '多人游戏初始化失败';
        
        if (error.message.includes('玩家数据')) {
          userMessage = '游戏数据异常，请重新开始游戏';
        } else if (error.message.includes('缺少必要字段')) {
          userMessage = '服务器数据不完整，请联系管理员';
        } else if (error.message.includes('连接')) {
          userMessage = '网络连接异常，请检查网络设置';
        }
        
        this.message = userMessage;
        this.messageType = 'error';
        this.gameStatus = 'lobby'; // 返回房间等待界面
        
        // 通知多人游戏store清理状态
        try {
          const { useMultiplayerStore } = await import('./multiplayer.js');
          const multiplayerStore = useMultiplayerStore();
          if (multiplayerStore && multiplayerStore.handleGameInitError) {
            multiplayerStore.handleGameInitError(error);
          }
        } catch (importError) {
          console.warn('无法通知多人游戏store:', importError);
        }
        
        throw error; // 重新抛出以供上层处理
      }
    },

    /**
     * 模拟多人游戏加载步骤
     */
    async simulateMultiplayerLoadingSteps() {
      const steps = [
        { delay: 200, message: '连接多人游戏...' },
        { delay: 300, message: '同步玩家信息...' },
        { delay: 400, message: '发牌中...' },
        { delay: 300, message: '准备游戏界面...' },
        { delay: 200, message: '即将开始...' }
      ];

      for (const step of steps) {
        this.message = step.message;
        await new Promise(resolve => setTimeout(resolve, step.delay));
      }
    },

    /**
     * 从多人游戏状态创建玩家对象
     */
    createPlayersFromMultiplayerState(gameState) {
      // 1. 数据结构验证
      if (!gameState) {
        console.error('游戏状态为空');
        throw new Error('游戏状态数据缺失');
      }
      
      if (!gameState.players || !Array.isArray(gameState.players)) {
        console.error('玩家数据无效:', gameState);
        throw new Error('玩家数据结构无效');
      }
      
      if (gameState.players.length !== 3) {
        console.error('玩家数量错误:', gameState.players.length);
        throw new Error('需要3名玩家');
      }
      
      const currentPlayerId = gameState.currentPlayerId;
      const personalCardsMap = gameState.personalCards || {};
      const collectedMap = gameState.collectedCards || {};
      
      // 2. 使用防御性编程
      const constructedPlayers = gameState.players.map((playerData, index) => {
        if (!playerData || typeof playerData !== 'object') {
          throw new Error(`玩家数据无效: 索引${index}`);
        }
        
        const isCurrentPlayer = playerData.id === currentPlayerId;
        const rawCards = personalCardsMap[playerData.id] || [];
        const rebuiltCards = this.rebuildPlayerCards(rawCards);
        const cardCountFromServer = Number(playerData.cardCount ?? rebuiltCards.length ?? 0);

        const player = new Player(
          playerData.id || `player_${index}`,
          playerData.name || `玩家${index + 1}`,
          playerData.isAI || false,
          isCurrentPlayer ? '😊' : (playerData.isAI ? '🤖' : '👤')
        );
        player.seatIndex = Number.isInteger(playerData.seatIndex)
          ? playerData.seatIndex
          : index;
        // 所有玩家统一重建牌对象，便于AI逻辑复用
        player.cards = rebuiltCards;
        player.cardCount = rebuiltCards.length > 0 ? rebuiltCards.length : cardCountFromServer;
        player.hiddenCardCount = Number.isFinite(cardCountFromServer) ? cardCountFromServer : player.cardCount;
        player.isHiddenHand = !isCurrentPlayer;
        player.collected = Number(collectedMap[player.id] || 0);
        return player;
      });

      // 按座位顺序排序，确保界面与逻辑一致
      constructedPlayers.sort((a, b) => a.seatIndex - b.seatIndex);
      
      return constructedPlayers;
    },

    /**
     * 查找当前玩家
     */
    findCurrentPlayer() {
      // 从gameState或通过其他方式确定当前玩家
      const currentPlayerId = this.gameEngine?.currentPlayerId;
      if (currentPlayerId) {
        return this.players.find(p => p.id === currentPlayerId);
      }
      return this.players[0]; // Fallback
    },

    /**
     * 创建多人游戏兼容的游戏引擎
     */
    createMultiplayerGameEngine(gameState) {
      // 创建一个兼容单人游戏接口的多人游戏引擎适配器
      const safeIndex = Number.isInteger(gameState.currentPlayerIndex) ? gameState.currentPlayerIndex : 0;

      const adapter = {
        players: this.players,
        currentPlayerIndex: safeIndex,
        currentPlayerId: gameState.currentPlayerId ?? (this.players?.[safeIndex]?.id ?? null),
        currentRound: gameState.currentRound ?? 1,
        roundCards: this.rebuildRoundCards(gameState.roundCards || []),
        collectedCards: { ...(gameState.collectedCards || {}) },
        gameStatus: gameState.gameStatus || 'playing',
        waitingForCollection: Boolean(gameState.waitingForCollection),
        roundWinner: gameState.roundWinner || null,
        firstPlayer: gameState.firstPlayer || null,
        isFirstRound: gameState.isFirstRound ?? true,
        kouLeStatus: gameState.kouLeStatus || { isActive: false },
        lastRoundWinner: gameState.lastRoundWinner || null,

        // 适配器方法
        getCurrentPlayer() {
          if (!Array.isArray(this.players)) return null;
          return this.players[this.currentPlayerIndex] || null;
        },

        calculatePlayPower(cards = []) {
          if (!Array.isArray(cards) || cards.length === 0) return 0;

          if (cards.length === 1) {
            return cards[0]?.power || 0;
          }

          if (cards.length === 2) {
            const [first, second] = cards;
            const isDaXiaoWangPair = cards.every(c => c && c.rank === 'joker') &&
              first?.displayName !== second?.displayName;
            const isRedErPair = cards.every(c => c && c.displayName === '红尔');

            if (isDaXiaoWangPair || isRedErPair) {
              return 125;
            }
            return (first?.power || 0) + 100;
          }

          if (cards.length >= 3) {
            const powers = cards
              .map(card => card?.power || 0)
              .filter(power => typeof power === 'number');
            if (powers.length === 0) return 0;
            return Math.max(...powers) + 200;
          }

          return 0;
        },

        validatePlay(playerId, cards = []) {
          if (!playerId || !Array.isArray(cards)) {
            return { valid: false, message: '出牌数据无效' };
          }

          const players = Array.isArray(this.players) ? this.players : [];
          const player = players.find(p => p?.id === playerId);
          if (!player) {
            return { valid: false, message: '玩家不存在' };
          }

          const currentPlayer = players[this.currentPlayerIndex];
          if (!currentPlayer || currentPlayer.id !== playerId) {
            return { valid: false, message: '不是你的回合' };
          }

          const ownedCards = Array.isArray(player.cards)
            ? player.cards.filter(card => card && typeof card.id === 'string')
            : [];
          const hasAllCards = cards.every(card =>
            ownedCards.some(existing => existing.id === card.id)
          );
          if (!hasAllCards) {
            return { valid: false, message: '你没有这些牌' };
          }

          if (cards.length < 1) {
            return { valid: false, message: '至少要出一张牌' };
          }

          if (cards.length === 2) {
            const firstCard = cards[0];
            const secondCard = cards[1];
            if (typeof firstCard?.canPairWith !== 'function' || !firstCard.canPairWith(secondCard)) {
              return { valid: false, message: '这两张牌不能组成对子' };
            }
          } else if (cards.length > 2) {
            const ququRanks = ['J', 'Q', 'K'];
            const allQuqu = cards.every(c => ququRanks.includes(c.rank));
            if (!allQuqu) {
              return { valid: false, message: '只有同色曲曲可以一起出多张' };
            }

            const redSuits = ['hearts', 'diamonds'];
            const firstIsRed = redSuits.includes(cards[0].suit);
            const allSameColor = cards.every(c => redSuits.includes(c.suit) === firstIsRed);
            if (!allSameColor) {
              return { valid: false, message: '多张曲曲必须颜色相同' };
            }
          }

          if (Array.isArray(this.roundCards) && this.roundCards.length > 0) {
            const firstPlay = this.roundCards[0];
            const requiredCount = Array.isArray(firstPlay?.cards) ? firstPlay.cards.length : 0;

            if (requiredCount > 0 && cards.length !== requiredCount) {
              return { valid: false, message: `必须出${requiredCount}张牌` };
            }

            const activePlays = this.roundCards.filter(play => play && !play.passed);
            const currentMaxPower = activePlays.length > 0
              ? Math.max(...activePlays.map(play => {
                  if (typeof play.power === 'number') return play.power;
                  return this.calculatePlayPower(play.cards || []);
                }))
              : 0;

            const playPower = this.calculatePlayPower(cards);

            if (playPower === currentMaxPower && playPower === 125) {
              return { valid: false, message: '大小王对和红尔对不分胜负，不能出牌' };
            }

            if (playPower <= currentMaxPower) {
              return { valid: false, message: '出的牌必须大于桌面上的牌' };
            }
          }

          return { valid: true };
        },

        calculateGameResults() {
          const results = [];

          this.players.forEach(player => {
            const collected = this.collectedCards[player.id] || 0;
            let level = '不够';
            let coins = 0;

            if (collected >= 18) {
              level = '此了';
              coins = 3;
            } else if (collected >= 15) {
              level = '五了';
              coins = 2;
            } else if (collected >= 9) {
              level = '刚够';
              coins = 1;
            }

            results.push({
              player: player,
              collected: collected,
              level: level,
              coins: coins
            });
          });

          // 计算支付关系
          const payments = this.calculatePayments(results);

          return {
            results: results,
            payments: payments
          };
        },

        calculatePayments(results) {
          const losers = results.filter(r => r.level === '不够');
          const winners = results.filter(r => r.level !== '不够');
          const payments = [];

          // 基础支付
          losers.forEach(loser => {
            winners.forEach(winner => {
              payments.push({
                from: loser.player.id,
                to: winner.player.id,
                amount: winner.coins,
                fromName: loser.player.name,
                toName: winner.player.name,
                type: 'base'
              });
            });
          });

          // 处理"宣"的风险支付
          if (this.kouLeStatus.xuanPlayers && this.kouLeStatus.xuanPlayers.length > 0) {
            const initiatorId = this.kouLeStatus.initiator;
            const initiatorResult = results.find(r => r.player.id === initiatorId);

            // 只有当发起"扣了"的玩家赢了，才需要处理风险支付
            if (initiatorResult && initiatorResult.level !== '不够') {
              this.kouLeStatus.xuanPlayers.forEach(xuanPlayerId => {
                const xuanResult = results.find(r => r.player.id === xuanPlayerId);

                // 如果"宣"的玩家输了
                if (xuanResult && xuanResult.level === '不够') {
                  // 需要额外支付给发起"扣了"的玩家
                  const riskAmount = initiatorResult.coins * this.kouLeStatus.riskMultiplier;
                  payments.push({
                    from: xuanPlayerId,
                    to: initiatorId,
                    amount: riskAmount,
                    fromName: xuanResult.player.name,
                    toName: initiatorResult.player.name,
                    type: 'risk',
                    riskMultiplier: this.kouLeStatus.riskMultiplier
                  });
                }
              });
            }
          }

          return payments;
        }
      };

      return adapter;
    },

    /**
     * 设置多人游戏回合提示消息
     */
    setMultiplayerTurnMessage() {
      const currentTurnPlayer = this.gameEngine.getCurrentPlayer();
      const firstPlayerName = this.gameEngine.firstPlayer?.name || '未知';
      
      if (currentTurnPlayer?.id === this.currentPlayer?.id) {
        this.message = `🎲 ${firstPlayerName}首出！多人游戏开始，轮到你出牌。`;
        audioManager.speak(`${firstPlayerName}首出，多人游戏开始，轮到你出牌`);
      } else {
        this.message = `🎲 ${firstPlayerName}首出！多人游戏开始，${currentTurnPlayer?.name}先出牌。`;
        audioManager.speak(`${firstPlayerName}首出，多人游戏开始，${currentTurnPlayer?.name}先出牌`);
      }
      this.messageType = 'info';
    },

    /**
     * 同步多人游戏状态（用于后续游戏过程中的状态更新）
     */
    syncMultiplayerState(multiplayerGameState) {
      if (this.gameMode !== 'multiplayer') return;

      console.log('syncMultiplayerState调用', multiplayerGameState);

      try {
        // 保存旧的waitingForCollection状态用于检测变化
        const oldWaitingForCollection = this.gameEngine?.waitingForCollection || false;
        const oldGameStatus = this.gameEngine?.gameStatus || 'playing';

        // 更新游戏引擎状态
        if (this.gameEngine) {
          this.gameEngine.currentPlayerIndex = multiplayerGameState.currentPlayerIndex;
          this.gameEngine.currentRound = multiplayerGameState.currentRound;

          // *** 关键修复：重建roundCards中的Card对象 ***
          this.gameEngine.roundCards = this.rebuildRoundCards(multiplayerGameState.roundCards || []);

          this.gameEngine.waitingForCollection = multiplayerGameState.waitingForCollection;
          this.gameEngine.roundWinner = multiplayerGameState.roundWinner;
          this.gameEngine.collectedCards = {
            ...(multiplayerGameState.collectedCards || {})
          };

          // *** 关键修复：同步游戏状态 ***
          this.gameEngine.gameStatus = multiplayerGameState.gameStatus || 'playing';
        }

        // *** 关键修复：检测收牌状态变化 ***
        if (!oldWaitingForCollection && multiplayerGameState.waitingForCollection) {
          // 进入收牌状态，启动倒计时
          console.log('检测到进入收牌状态，启动倒计时');
          // 获取赢家信息
          const winnerFromEngine = this.gameEngine.roundWinner;
          const winner = winnerFromEngine ? this.players.find(p => p.id === winnerFromEngine.id) : null;
          const winnerName = winner?.name || '无人';

          // 语音播报
          if (winner?.id === this.currentPlayer?.id) {
            audioManager.speak(`你赢得本轮`);
          } else {
            audioManager.speak(`${winnerName}赢得本轮`);
          }

          // 启动收牌倒计时（多人模式也用同样的逻辑）
          this.collectCountdown = 3;
          this.message = `${winnerName}赢得本轮，3秒后自动收牌`;
          this.messageType = 'info';

          // 清除之前的倒计时定时器（如果有）
          if (this.countdownTimer) {
            clearInterval(this.countdownTimer);
          }

          this.countdownTimer = setInterval(() => {
            this.collectCountdown--;
            if (this.collectCountdown <= 0) {
              clearInterval(this.countdownTimer);
              this.collectCards();
            }
          }, 1000);
        } else if (oldWaitingForCollection && !multiplayerGameState.waitingForCollection) {
          // 收牌完成，清除倒计时显示
          console.log('检测到收牌完成，清除倒计时');
          this.collectCountdown = 0;
          this.showingRoundResult = false;
          if (this.countdownTimer) {
            clearInterval(this.countdownTimer);
            this.countdownTimer = null;
          }
          if (this.roundResultTimer) {
            clearTimeout(this.roundResultTimer);
            this.roundResultTimer = null;
          }
        }
        
        // 更新玩家手牌
        const byId = new Map(this.players.map(p => [p.id, p]));
        const personalCardsMap = multiplayerGameState.personalCards || {};

        const collectedMap = this.gameEngine?.collectedCards || {};
        this.players.forEach(player => {
          player.collected = collectedMap[player.id] || 0;
        });

        // *** 关键修复：重建当前玩家手牌Card对象 ***
        if (this.currentPlayer && multiplayerGameState.personalCards) {
          const newCards = multiplayerGameState.personalCards[this.currentPlayer.id];
          if (Array.isArray(newCards)) {
            const me = byId.get(this.currentPlayer.id);
            me.cards = this.rebuildPlayerCards(newCards);
            me.cardCount = me.cards.length;
            me.hiddenCardCount = me.cardCount;
          }
        }

        // 更新其他玩家的手牌与张数
        if (Array.isArray(multiplayerGameState.players)) {
          multiplayerGameState.players.forEach(pd => {
            if (!pd) return;
            const p = byId.get(pd.id);
            if (p) {
              if (Number.isInteger(pd.seatIndex)) {
                p.seatIndex = pd.seatIndex;
              }
              const cardData = personalCardsMap[pd.id];
              if (Array.isArray(cardData) && cardData.length > 0) {
                p.cards = this.rebuildPlayerCards(cardData);
                p.cardCount = p.cards.length;
              } else {
                const count = Number(pd.cardCount || 0);
                p.cardCount = count;
                p.cards = Array.from({ length: count });
              }
              p.hiddenCardCount = p.cardCount;
              p.collected = collectedMap[p.id] || 0;
            }
          });
        }

        if (this.currentPlayer) {
          const currentPlayerData = Array.isArray(multiplayerGameState.players)
            ? multiplayerGameState.players.find(p => p.id === this.currentPlayer.id)
            : null;
          if (currentPlayerData && Number.isInteger(currentPlayerData.seatIndex)) {
            this.currentPlayer.seatIndex = currentPlayerData.seatIndex;
          }
        }
        
        // 更新UI状态
        this.updateRoundInfo();

        // *** 关键修复：检测游戏结束状态变化 ***
        if (oldGameStatus !== 'finished' && multiplayerGameState.gameStatus === 'finished') {
          console.log('检测到游戏结束，调用endGame()');
          // 游戏刚刚结束，调用结束处理
          this.endGame();
          return; // 游戏结束后不再检查AI回合
        }

        console.log('syncMultiplayerState完成');

      } catch (error) {
        console.error('同步多人游戏状态失败:', error);
        this.handleError('syncMultiplayerState', error, '游戏状态同步失败，请刷新页面');
      }

      // 检查是否需要AI出牌（在状态同步后）
      setTimeout(() => {
        this.checkAITurn();
      }, 100);
    },

    // 多人模式AI出牌检查 - 增强版本
    checkMultiplayerAITurn() {
      if (this.gameMode !== 'multiplayer') return;
      
      // 检查游戏状态
      if (this.gameStatus !== 'playing') {
        console.log('游戏未在进行中，跳过AI检查');
        return;
      }
      
      // 检查是否等待收牌
      if (this.gameEngine?.waitingForCollection) {
        console.log('等待收牌中，跳过AI检查');
        return;
      }
      
      // 获取当前轮到的玩家
      const currentTurnPlayer = this.gameEngine?.getCurrentPlayer();
      if (!currentTurnPlayer) {
        console.log('无法获取当前玩家，跳过AI检查');
        return;
      }
      
      // 检查是否为AI玩家
      if (!currentTurnPlayer.isAI) {
        console.log(`当前玩家${currentTurnPlayer.name}非AI，跳过检查`);
        return;
      }
      
      console.log(`检测到AI玩家${currentTurnPlayer.name}回合，准备出牌`);
      
      // 使用配置化延迟和超时保护
      const aiOperationId = `${currentTurnPlayer.id}_${Date.now()}`;
      
      // 设置AI超时保护
      this.setupAITimeoutProtection(aiOperationId, currentTurnPlayer);
      
      // 延迟执行AI出牌
      const aiTimer = setTimeout(() => {
        this.executeMultiplayerAIMove(currentTurnPlayer, aiOperationId);
      }, AI_CONFIG.delays.aiThinking);
      
      // 存储定时器引用以便清理
      this.aiOperationTimers.set(aiOperationId, aiTimer);
    },

    /**
     * 设置AI超时保护机制
     */
    setupAITimeoutProtection(operationId, aiPlayer) {
      if (!this.aiTimeoutProtection.enabled) return;
      
      // 清理之前的超时定时器
      if (this.aiTimeoutProtection.activeTimeout) {
        clearTimeout(this.aiTimeoutProtection.activeTimeout);
      }
      
      this.aiTimeoutProtection.activeTimeout = setTimeout(() => {
        console.warn(`AI玩家${aiPlayer.name}出牌超时，执行降级策略`);
        this.handleAITimeout(operationId, aiPlayer);
      }, AI_CONFIG.timeouts.aiDecision);
    },

    /**
     * 处理AI超时
     */
    handleAITimeout(operationId, aiPlayer) {
      // 清理相关定时器
      this.cleanupAIOperation(operationId);
      
      // 增加降级计数
      this.aiTimeoutProtection.fallbackCount++;
      
      // 显示超时消息
      this.message = `${aiPlayer.name}思考超时，使用快速决策...`;
      this.messageType = 'warning';
      
      // 执行降级策略
      this.executeFallbackAIStrategy(aiPlayer);
      
      // 记录性能指标
      this.recordPerformanceMetric('ai_timeout', {
        playerId: aiPlayer.id,
        fallbackCount: this.aiTimeoutProtection.fallbackCount
      });
    },

    /**
     * 执行AI降级策略
     */
    async executeFallbackAIStrategy(aiPlayer) {
      try {
        // 使用简化的AI逻辑快速决策
        const quickDecision = this.makeQuickAIDecision(aiPlayer);
        
        if (quickDecision) {
          await this.sendMultiplayerAIAction(quickDecision);
        } else {
          // 如果快速决策也失败，强制扣牌
          await this.forceAIPass(aiPlayer);
        }
      } catch (error) {
        console.error('AI降级策略执行失败:', error);
        await this.forceAIPass(aiPlayer);
      }
    },

    /**
     * 快速AI决策（简化版）
     */
    makeQuickAIDecision(aiPlayer) {
      try {
        const isFirstPlay = !this.gameEngine?.roundCards || this.gameEngine.roundCards.length === 0;
        
        if (isFirstPlay) {
          // 简单首出：出最小单牌
          const cards = aiPlayer.cards || [];
          if (cards.length > 0) {
            const minCard = cards[cards.length - 1];
            return {
              type: 'play_cards',
              playerId: aiPlayer.id,
              cards: [minCard],
              action: 'play'
            };
          }
        } else {
          // 简单跟牌：直接扣牌
          return {
            type: 'pass_turn',
            playerId: aiPlayer.id,
            discardCards: this.selectMinimalDiscardCards(aiPlayer),
            action: 'pass'
          };
        }
      } catch (error) {
        console.error('快速AI决策失败:', error);
      }
      return null;
    },

    /**
     * 选择最少扣牌
     */
    selectMinimalDiscardCards(aiPlayer) {
      const firstPlay = this.gameEngine?.roundCards?.[0];
      const requiredCount = firstPlay?.cards?.length || 1;
      
      if (aiPlayer.cards && aiPlayer.cards.length > 0) {
        return aiPlayer.cards.slice(-requiredCount);
      }
      
      return [];
    },

    /**
     * 强制AI扣牌
     */
    async forceAIPass(aiPlayer) {
      try {
        const discardCards = this.selectMinimalDiscardCards(aiPlayer);
        await this.sendMultiplayerAIAction({
          type: 'pass_turn',
          playerId: aiPlayer.id,
          discardCards,
          action: 'pass'
        });
      } catch (error) {
        console.error('强制AI扣牌失败:', error);
        // 最后的错误处理
        this.handleCriticalAIError(aiPlayer, error);
      }
    },

    /**
     * 处理严重AI错误
     */
    handleCriticalAIError(aiPlayer, error) {
      console.error('AI操作严重错误:', error);
      
      this.message = `${aiPlayer.name}遇到技术问题，游戏可能需要重新开始`;
      this.messageType = 'error';
      
      // 触发错误恢复机制
      this.triggerErrorRecovery('critical_ai_error', {
        playerId: aiPlayer.id,
        error: error.message
      });
    },

    /**
     * 执行多人模式AI出牌 - 增强版本
     */
    async executeMultiplayerAIMove(aiPlayer, operationId) {
      const startTime = Date.now();
      
      try {
        console.log(`${aiPlayer.name}开始AI决策 [操作ID: ${operationId}]`);
        
        // 清理超时保护（正常流程开始）
        if (this.aiTimeoutProtection.activeTimeout) {
          clearTimeout(this.aiTimeoutProtection.activeTimeout);
          this.aiTimeoutProtection.activeTimeout = null;
        }
        
        // 使用单机模式的AI逻辑进行决策，增加超时控制
        const aiDecision = await Promise.race([
          this.makeAIDecisionForMultiplayerAsync(aiPlayer),
          this.createDecisionTimeout(AI_CONFIG.timeouts.aiDecision / 2)
        ]);
        
        if (!aiDecision) {
          throw new Error(`${aiPlayer.name}AI决策失败：未返回有效决策`);
        }
        
        // 记录决策时间
        const decisionTime = Date.now() - startTime;
        this.recordPerformanceMetric('ai_decision_time', decisionTime);
        
        // 通过WebSocket发送AI出牌操作
        await this.sendMultiplayerAIAction(aiDecision);
        
        // 清理操作
        this.cleanupAIOperation(operationId);
        
        console.log(`${aiPlayer.name}AI决策完成，耗时: ${decisionTime}ms`);
        
      } catch (error) {
        console.error(`${aiPlayer.name}AI出牌执行失败:`, error);
        
        // 清理操作
        this.cleanupAIOperation(operationId);
        
        // 记录错误
        this.recordPerformanceMetric('ai_error', {
          playerId: aiPlayer.id,
          error: error.message,
          duration: Date.now() - startTime
        });
        
        // 降级处理
        this.handleMultiplayerAIError(aiPlayer, error);
      }
    },

    /**
     * 异步AI决策（支持超时）
     */
    async makeAIDecisionForMultiplayerAsync(aiPlayer) {
      return new Promise((resolve) => {
        // 在下个事件循环中执行，避免阻塞UI
        setTimeout(() => {
          try {
            const decision = this.makeAIDecisionForMultiplayer(aiPlayer);
            resolve(decision);
          } catch (error) {
            console.error('异步AI决策失败:', error);
            resolve(null);
          }
        }, 0);
      });
    },

    /**
     * 创建决策超时Promise
     */
    createDecisionTimeout(timeout) {
      return new Promise((_, reject) => {
        setTimeout(() => {
          reject(new Error('AI决策超时'));
        }, timeout);
      });
    },

    /**
     * 清理AI操作相关资源
     */
    cleanupAIOperation(operationId) {
      // 清理定时器
      if (this.aiOperationTimers.has(operationId)) {
        clearTimeout(this.aiOperationTimers.get(operationId));
        this.aiOperationTimers.delete(operationId);
      }
      
      // 清理超时保护
      if (this.aiTimeoutProtection.activeTimeout) {
        clearTimeout(this.aiTimeoutProtection.activeTimeout);
        this.aiTimeoutProtection.activeTimeout = null;
      }
    },

    /**
     * 记录性能指标
     */
    recordPerformanceMetric(type, data) {
      if (!AI_CONFIG.monitoring.enablePerformanceTracking) return;
      
      const metric = {
        type,
        data,
        timestamp: Date.now()
      };
      
      switch (type) {
        case 'ai_decision_time':
          this.performanceMetrics.aiDecisionTimes.push(data);
          // 保持最近100条记录
          if (this.performanceMetrics.aiDecisionTimes.length > 100) {
            this.performanceMetrics.aiDecisionTimes.shift();
          }
          
          // 性能警告阈值检查
          if (data > AI_CONFIG.monitoring.performanceLogThreshold) {
            console.warn(`AI决策时间过长: ${data}ms`);
          }
          break;
          
        default:
          console.debug('性能指标记录:', metric);
      }
      
      this.performanceMetrics.operationCount++;
    },

    /**
     * 为多人模式制定AI决策（复用单机逻辑）
     */
    makeAIDecisionForMultiplayer(aiPlayer) {
      try {
        // 检查是否首轮出牌
        const isFirstPlay = !this.gameEngine?.roundCards || this.gameEngine.roundCards.length === 0;
        
        if (isFirstPlay) {
          // 首轮出牌决策
          return this.makeFirstPlayDecision(aiPlayer);
        } else {
          // 跟牌决策
          return this.makeFollowPlayDecision(aiPlayer);
        }
      } catch (error) {
        console.error(`AI决策制定失败:`, error);
        return null;
      }
    },

    /**
     * AI首轮出牌决策
     */
    makeFirstPlayDecision(aiPlayer) {
      // 使用与单机模式相同的AI策略
      const bestPlay = this.selectBestFirstPlayForAI(aiPlayer);
      
      return {
        type: 'play_cards',
        playerId: aiPlayer.id,
        cards: bestPlay,
        action: 'play'
      };
    },

    /**
     * AI跟牌决策
     */
    makeFollowPlayDecision(aiPlayer) {
      const firstPlay = this.gameEngine.roundCards[0];
      const requiredCount = firstPlay.cards.length;
      const currentMaxPower = Math.max(
        ...this.gameEngine.roundCards
          .filter(p => !p.passed)
          .map(p => p.power)
      );
      
      // 查找可能的出牌组合
      const possiblePlays = this.findPossiblePlaysForAI(aiPlayer, requiredCount);
      const winningPlays = possiblePlays.filter(play => {
        const power = this.calculatePlayPowerForAI(play);
        return power > currentMaxPower;
      });
      
      if (winningPlays.length > 0) {
        // 选择最佳出牌
        const bestPlay = this.selectBestAIPlayForMultiplayer(aiPlayer, winningPlays, currentMaxPower);
        return {
          type: 'play_cards',
          playerId: aiPlayer.id,
          cards: bestPlay,
          action: 'play'
        };
      } else {
        // 扣牌
        return {
          type: 'pass_turn',
          playerId: aiPlayer.id,
          discardCards: this.selectDiscardCardsForAI(aiPlayer, requiredCount),
          action: 'pass'
        };
      }
    },

    /**
     * 发送多人模式AI操作
     */
    async sendMultiplayerAIAction(aiDecision) {
      const { useMultiplayerStore } = await import('./multiplayer.js');
      const multiplayerStore = useMultiplayerStore();
      
      if (!multiplayerStore.connected) {
        throw new Error('WebSocket连接已断开');
      }
      
      console.log('发送AI操作:', aiDecision);
      
      if (aiDecision.action === 'play') {
        // 发送出牌操作
        const result = await multiplayerStore.playCards(aiDecision.cards, aiDecision.playerId);
        console.log('AI出牌结果:', result);
      } else if (aiDecision.action === 'pass') {
        // 发送扣牌操作
        const result = await multiplayerStore.passTurn(aiDecision.discardCards, aiDecision.playerId);
        console.log('AI扣牌结果:', result);
      }
    },

    /**
     * 处理多人模式AI错误 - 增强版本
     */
    handleMultiplayerAIError(aiPlayer, error) {
      console.error(`多人模式AI错误处理:`, error);
      
      // 错误分级处理
      const errorLevel = this.classifyError(error);
      
      switch (errorLevel) {
        case 'critical':
          this.handleCriticalAIError(aiPlayer, error);
          break;
          
        case 'recoverable':
          this.handleRecoverableAIError(aiPlayer, error);
          break;
          
        default:
          this.handleMinorAIError(aiPlayer, error);
      }
    },

    /**
     * 错误分级
     */
    classifyError(error) {
      const errorMessage = error.message?.toLowerCase() || '';
      
      // 严重错误
      if (errorMessage.includes('websocket') && errorMessage.includes('closed')) {
        return 'critical';
      }
      
      if (errorMessage.includes('timeout') || errorMessage.includes('超时')) {
        return 'recoverable';
      }
      
      if (errorMessage.includes('network') || errorMessage.includes('连接')) {
        return 'recoverable';
      }
      
      return 'minor';
    },

    /**
     * 处理可恢复的AI错误
     */
    async handleRecoverableAIError(aiPlayer, error) {
      console.log(`处理可恢复AI错误: ${error.message}`);
      
      // 显示用户友好的错误信息
      this.message = `${aiPlayer.name}网络异常，正在重试...`;
      this.messageType = 'warning';
      
      try {
        // 尝试重连WebSocket
        await this.attemptReconnectForAI();
        
        // 验证游戏状态后重试
        await this.validateGameStateAfterReconnect();
        
        // 使用配置的重试延迟
        setTimeout(() => {
          if (this.gameStatus === 'playing') {
            console.log('重连后重新检查AI回合');
            this.checkMultiplayerAITurn();
          }
        }, AI_CONFIG.delays.errorRetry);
        
      } catch (reconnectError) {
        console.error('重连失败:', reconnectError);
        this.handleCriticalAIError(aiPlayer, reconnectError);
      }
    },

    /**
     * 处理轻微AI错误
     */
    handleMinorAIError(aiPlayer, error) {
      console.log(`处理轻微AI错误: ${error.message}`);
      
      this.message = `${aiPlayer.name}正在重新思考...`;
      this.messageType = 'info';
      
      // 短暂延迟后重试
      setTimeout(() => {
        if (this.gameStatus === 'playing') {
          this.checkMultiplayerAITurn();
        }
      }, AI_CONFIG.retries.baseDelay);
    },

    /**
     * 验证重连后的游戏状态
     */
    async validateGameStateAfterReconnect() {
      try {
        const { useMultiplayerStore } = await import('./multiplayer.js');
        const multiplayerStore = useMultiplayerStore();
        
        // 检查连接状态
        if (!multiplayerStore.connected) {
          throw new Error('WebSocket连接未恢复');
        }
        
        // 检查房间状态
        if (!multiplayerStore.roomId) {
          throw new Error('房间信息丢失');
        }
        
        // 检查游戏状态
        if (!multiplayerStore.multiplayerGameState) {
          console.warn('多人游戏状态需要重新同步');
        }
        
        console.log('游戏状态验证通过');
        
      } catch (error) {
        console.error('游戏状态验证失败:', error);
        throw error;
      }
    },

    /**
     * 触发错误恢复机制
     */
    triggerErrorRecovery(errorType, data) {
      console.log(`触发错误恢复: ${errorType}`, data);
      
      // 发送错误事件
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('game-error-recovery', {
          detail: {
            type: errorType,
            data,
            timestamp: Date.now()
          }
        }));
      }
      
      // 根据错误类型采取恢复措施
      switch (errorType) {
        case 'critical_ai_error':
          this.initiateCriticalRecovery();
          break;
          
        case 'connection_lost':
          this.initiateConnectionRecovery();
          break;
          
        default:
          console.warn(`未知错误类型: ${errorType}`);
      }
    },

    /**
     * 启动严重错误恢复
     */
    async initiateCriticalRecovery() {
      console.log('启动严重错误恢复流程');
      
      this.message = '游戏遇到严重问题，正在尝试恢复...';
      this.messageType = 'error';
      
      try {
        // 清理所有AI操作
        this.cleanupAllAIOperations();
        
        // 重置AI状态
        this.resetAIState();
        
        // 尝试重新连接
        await this.attemptReconnectForAI();
        
        this.message = '系统恢复成功，游戏继续';
        this.messageType = 'success';
        
      } catch (error) {
        console.error('严重错误恢复失败:', error);
        this.message = '系统恢复失败，请重新开始游戏';
        this.messageType = 'error';
      }
    },

    /**
     * 启动连接恢复
     */
    async initiateConnectionRecovery() {
      console.log('启动连接恢复流程');
      
      this.message = '网络连接异常，正在重连...';
      this.messageType = 'warning';
      
      await this.attemptReconnectForAI();
    },

    /**
     * 清理所有AI操作
     */
    cleanupAllAIOperations() {
      // 清理所有AI操作定时器
      for (const [operationId, timer] of this.aiOperationTimers) {
        clearTimeout(timer);
      }
      this.aiOperationTimers.clear();
      
      // 清理超时保护
      if (this.aiTimeoutProtection.activeTimeout) {
        clearTimeout(this.aiTimeoutProtection.activeTimeout);
        this.aiTimeoutProtection.activeTimeout = null;
      }
    },

    /**
     * 重置AI状态
     */
    resetAIState() {
      this.aiTimeoutProtection.fallbackCount = 0;
      this.performanceMetrics.operationCount = 0;
      this.performanceMetrics.aiDecisionTimes = [];
    },

    /**
     * 为AI重连WebSocket
     */
    async attemptReconnectForAI() {
      try {
        const { useMultiplayerStore } = await import('./multiplayer.js');
        const multiplayerStore = useMultiplayerStore();
        
        if (!multiplayerStore.connected) {
          console.log('尝试为AI重连WebSocket');
          await multiplayerStore.connect();
        }
      } catch (error) {
        console.error('WebSocket重连失败:', error);
      }
    },

    /**
     * 为多人模式复用单机AI逻辑的工具方法
     */

    // 复用单机模式的AI首出策略
    selectBestFirstPlayForAI(player) {
      // 直接使用GameEngine的selectBestFirstPlay逻辑
      // 临时创建一个本地GameEngine实例来计算
      const tempEngine = {
        collectedCards: this.gameEngine?.collectedCards || {},
        findAllPairs: (p) => this.findAllPairsForAI(p),
        calculatePlayPower: (cards) => this.calculatePlayPowerForAI(cards)
      };
      
      return this.selectBestFirstPlayLogic(player, tempEngine);
    },

    // 复用AI逻辑核心算法
    selectBestFirstPlayLogic(player, engine) {
      const remainingCards = player.cards.length;
      const currentCollected = engine.collectedCards[player.id] || 0;
      const needMoreCards = currentCollected < 9;
      const urgentNeed = currentCollected < 6;
      
      const averagePower = player.cards.reduce((sum, card) => sum + card.power, 0) / player.cards.length;
      const hasStrongCards = player.cards.some(card => card.power >= 22);
      const isWeakHand = averagePower < 18;
      
      // 策略1：红曲曲三张
      const redQuqu = player.cards.filter(c =>
        ['J', 'Q', 'K'].includes(c.rank) && ['hearts', 'diamonds'].includes(c.suit)
      );
      if (redQuqu.length >= 3) {
        return redQuqu.slice(0, 3);
      }
      
      // 策略2：黑曲曲三张
      const blackQuqu = player.cards.filter(c =>
        ['J', 'Q', 'K'].includes(c.rank) && ['spades', 'clubs'].includes(c.suit)
      );
      if (blackQuqu.length >= 3) {
        if (needMoreCards || isWeakHand || remainingCards <= 6) {
          return blackQuqu.slice(0, 3);
        }
        if (Math.random() > 0.1) {
          return blackQuqu.slice(0, 3);
        }
      }
      
      // 策略3：对子策略
      const pairs = engine.findAllPairs(player);
      if (pairs.length > 0) {
        pairs.sort((a, b) => engine.calculatePlayPower(b) - engine.calculatePlayPower(a));
        const topPair = pairs[0];
        const topPairPower = engine.calculatePlayPower(topPair);
        
        if (topPairPower >= 125) {
          if (urgentNeed || needMoreCards || Math.random() > 0.05) {
            return topPair;
          }
        }
        
        if (topPairPower >= 121) {
          if (needMoreCards && Math.random() > 0.1) {
            return topPair;
          }
          if (isWeakHand && Math.random() > 0.2) {
            return topPair;
          }
        }
      }
      
      // 策略4：单张牌
      const selectedCard = this.selectSmartSingleCardForAI(player);
      return [selectedCard];
    },

    // 辅助工具方法
    findAllPairsForAI(player) {
      const pairs = [];
      for (let i = 0; i < player.cards.length - 1; i++) {
        for (let j = i + 1; j < player.cards.length; j++) {
          if (player.cards[i].canPairWith(player.cards[j])) {
            pairs.push([player.cards[i], player.cards[j]]);
          }
        }
      }
      return pairs;
    },

    calculatePlayPowerForAI(cards) {
      if (!cards || cards.length === 0) return 0;
      
      if (cards.length === 1) {
        return cards[0].power;
      }
      
      if (cards.length === 2) {
        const isDaXiaoWangPair = cards.every(c => c.rank === 'joker') &&
                                cards[0].displayName !== cards[1].displayName;
        const isRedErPair = cards.every(c => c.displayName === '红尔');
        
        if (isDaXiaoWangPair || isRedErPair) {
          return 125;
        } else {
          return cards[0].power + 100;
        }
      }
      
      if (cards.length >= 3) {
        const maxPower = Math.max(...cards.map(c => c.power));
        return maxPower + 200;
      }
      
      return 0;
    },

    selectSmartSingleCardForAI(player) {
      // 找出所有能组成对子的牌
      const pairCards = new Set();
      for (let i = 0; i < player.cards.length - 1; i++) {
        for (let j = i + 1; j < player.cards.length; j++) {
          if (player.cards[i].canPairWith(player.cards[j])) {
            pairCards.add(player.cards[i].id);
            pairCards.add(player.cards[j].id);
          }
        }
      }
      
      // 找出不会拆散对子的单牌
      const safeCards = player.cards.filter(card => !pairCards.has(card.id));
      
      if (safeCards.length > 0) {
        return safeCards[safeCards.length - 1]; // 最小的安全牌
      }
      
      // 如果没有安全牌，选择最小的牌
      return player.cards[player.cards.length - 1];
    },

    findPossiblePlaysForAI(player, requiredCount) {
      const possiblePlays = [];
      
      if (requiredCount === 1) {
        player.cards.forEach(card => {
          possiblePlays.push([card]);
        });
      } else if (requiredCount === 2) {
        for (let i = 0; i < player.cards.length - 1; i++) {
          for (let j = i + 1; j < player.cards.length; j++) {
            if (player.cards[i].canPairWith(player.cards[j])) {
              possiblePlays.push([player.cards[i], player.cards[j]]);
            }
          }
        }
      } else {
        const ququRanks = ['J', 'Q', 'K'];
        const redQu = player.cards.filter(c => ququRanks.includes(c.rank) && ['hearts', 'diamonds'].includes(c.suit));
        const blackQu = player.cards.filter(c => ququRanks.includes(c.rank) && ['spades', 'clubs'].includes(c.suit));
        
        if (redQu.length >= requiredCount) {
          this.getCombinationsForAI(redQu, requiredCount).forEach(combo => {
            possiblePlays.push(combo);
          });
        }
        if (blackQu.length >= requiredCount) {
          this.getCombinationsForAI(blackQu, requiredCount).forEach(combo => {
            possiblePlays.push(combo);
          });
        }
      }
      
      return possiblePlays;
    },

    getCombinationsForAI(arr, size) {
      const result = [];
      
      function combine(start, combo) {
        if (combo.length === size) {
          result.push([...combo]);
          return;
        }
        
        for (let i = start; i < arr.length; i++) {
          combo.push(arr[i]);
          combine(i + 1, combo);
          combo.pop();
        }
      }
      
      combine(0, []);
      return result;
    },

    selectBestAIPlayForMultiplayer(player, winningPlays, currentPower) {
      const currentCollected = this.gameEngine?.collectedCards?.[player.id] || 0;
      const needMoreCards = currentCollected < 9;
      const urgentNeed = currentCollected < 6;
      const canBeConservative = currentCollected >= 12;
      
      winningPlays.sort((a, b) => {
        const powerA = this.calculatePlayPowerForAI(a);
        const powerB = this.calculatePlayPowerForAI(b);
        return powerA - powerB;
      });
      
      // 如果需要收牌，优先选择强牌
      if (urgentNeed) {
        // 查找强力组合
        const strongPlays = winningPlays.filter(play => {
          const power = this.calculatePlayPowerForAI(play);
          return power >= 120; // 强对子或三张牌
        });
        
        if (strongPlays.length > 0) {
          return strongPlays[0];
        }
      }
      
      // 默认选择最小能赢的牌
      return winningPlays[0];
    },

    selectDiscardCardsForAI(player, requiredCount) {
      // 选择最小的牌作为扣牌
      const sortedCards = [...player.cards].sort((a, b) => a.power - b.power);
      return sortedCards.slice(0, requiredCount);
    },

    // ========== 内存管理和定时器清理 ==========

    /**
     * 内存管理和垃圾回收
     */
    performMemoryCleanup() {
      if (!AI_CONFIG.monitoring.enablePerformanceTracking) return;
      
      const now = Date.now();
      
      // 清理过期的性能指标（保留最近1小时的数据）
      const oneHour = 60 * 60 * 1000;
      this.performanceMetrics.aiDecisionTimes = this.performanceMetrics.aiDecisionTimes
        .filter(time => (now - time) < oneHour);
      
      // 强制垃圾回收（如果可用）
      if (typeof window !== 'undefined' && window.gc) {
        try {
          window.gc();
          console.debug('执行手动垃圾回收');
        } catch (error) {
          console.debug('手动垃圾回收不可用');
        }
      }
      
      this.performanceMetrics.lastGCTime = now;
    },

    /**
     * 定时器统一清理
     */
    clearAllTimers() {
      // 清理游戏相关定时器
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
        this.countdownTimer = null;
      }
      
      if (this.roundResultTimer) {
        clearTimeout(this.roundResultTimer);
        this.roundResultTimer = null;
      }
      
      if (this.wuxiangTimer) {
        clearInterval(this.wuxiangTimer);
        this.wuxiangTimer = null;
      }
      
      if (this.kouLeTimer) {
        clearInterval(this.kouLeTimer);
        this.kouLeTimer = null;
      }
      
      // 清理AI操作定时器
      this.cleanupAllAIOperations();
      
      console.debug('所有定时器已清理');
    },

    /**
     * 启动内存监控
     */
    startMemoryMonitoring() {
      if (!AI_CONFIG.monitoring.enablePerformanceTracking) return;
      
      setInterval(() => {
        this.performMemoryCleanup();
      }, AI_CONFIG.monitoring.memoryCheckInterval);
      
      console.debug('内存监控已启动');
    },

    // ========== Card对象重建方法 ==========

    /**
     * 重建roundCards中的Card对象
     */
    rebuildRoundCards(roundCardsData) {
      if (!Array.isArray(roundCardsData)) {
        console.warn('roundCardsData不是数组:', roundCardsData);
        return [];
      }

      const result = roundCardsData.map(playData => {
        try {
          // 保留非Card属性
          const rebuilt = {
            player: playData.player,
            power: playData.power,
            passed: playData.passed
          };

          // 重建cards数组
          if (Array.isArray(playData.cards)) {
            rebuilt.cards = this.rebuildPlayerCards(playData.cards);
          } else {
            rebuilt.cards = [];
          }

          // 重建discardedCards（如果存在）
          if (Array.isArray(playData.discardedCards)) {
            rebuilt.discardedCards = this.rebuildPlayerCards(playData.discardedCards);
          }

          return rebuilt;
        } catch (error) {
          console.error('重建roundCard失败:', error, playData);
          return {
            player: playData.player || {},
            cards: [],
            power: 0,
            passed: true
          };
        }
      });

      // 调试日志：输出重建后的roundCards
      if (result.length > 0) {
        console.log('[重建roundCards] 重建完成:', result.map(r => ({
          player: r.player?.name,
          cardsCount: r.cards?.length,
          passed: r.passed
        })));
      }

      return result;
    },

    /**
     * 重建玩家手牌Card对象
     */
    rebuildPlayerCards(cardsData) {
      if (!Array.isArray(cardsData)) {
        console.warn('cardsData不是数组:', cardsData);
        return [];
      }
      
      return cardsData.map(cardData => {
        try {
          // 使用Card.fromJSON方法重建
          if (cardData && typeof cardData === 'object') {
            // 检查是否已经是Card实例
            if (typeof cardData.getColor === 'function') {
              return cardData; // 已经是完整的Card实例
            }
            
            // 从JSON数据重建Card实例
            return Card.fromJSON(cardData);
          }
          
          console.warn('无效的card数据:', cardData);
          return this.createFallbackCard(cardData);
        } catch (error) {
          console.error('重建Card失败:', error, cardData);
          return this.handleCardRebuildError(error, cardData, 'rebuildPlayerCards');
        }
      }).filter(card => card !== null);
    },

    // ========== 数据验证工具函数 ==========

    /**
     * 验证多人游戏数据结构
     */
    validateMultiplayerGameState(gameState) {
      const errors = [];
      
      if (!gameState) {
        errors.push('游戏状态数据为空');
        return { isValid: false, errors };
      }
      
      if (!gameState.players) {
        errors.push('缺少玩家数据');
      } else if (!Array.isArray(gameState.players)) {
        errors.push('玩家数据格式无效');
      } else if (gameState.players.length !== 3) {
        errors.push(`玩家数量错误: ${gameState.players.length}，需要3名玩家`);
      }
      
      // 验证每个玩家数据
      if (Array.isArray(gameState.players)) {
        gameState.players.forEach((player, index) => {
          if (!player) {
            errors.push(`玩家${index + 1}数据为空`);
          } else {
            if (!player.id) errors.push(`玩家${index + 1}缺少ID`);
            if (!player.name) errors.push(`玩家${index + 1}缺少名称`);
          }
        });
      }
      
      return {
        isValid: errors.length === 0,
        errors
      };
    },

    /**
     * 安全的数组处理函数
     */
    safeMap(array, callback, fallback = []) {
      if (!Array.isArray(array)) {
        console.warn('safeMap: 输入不是数组', array);
        return fallback;
      }
      
      try {
        return array.map(callback);
      } catch (error) {
        console.error('safeMap: 处理失败', error);
        return fallback;
      }
    },

    /**
     * 通用错误处理器
     */
    handleError(context, error, userMessage = '操作失败，请重试') {
      console.error(`[${context}] 错误:`, error);
      
      this.lastError = error.message;
      this.messageType = 'error';
      this.message = userMessage;
      
      // 发送错误事件供UI组件监听
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('game-error', {
          detail: {
            context,
            error: error.message,
            userMessage,
            timestamp: new Date().toISOString()
          }
        }));
      }
      
      return {
        success: false,
        error: {
          code: error.code || 'UNKNOWN_ERROR',
          message: error.message,
          userMessage
        }
      };
    },

    // ========== Card对象验证和安全访问方法 ==========

    /**
     * 验证Card对象的完整性
     */
    validateCardObject(card, context = 'unknown') {
      if (!card) {
        console.warn(`[${context}] Card对象为空`);
        return false;
      }
      
      if (typeof card !== 'object') {
        console.warn(`[${context}] Card不是对象:`, typeof card);
        return false;
      }
      
      // 验证必需方法
      const requiredMethods = ['getColor', 'getSymbol', 'canPairWith'];
      for (const method of requiredMethods) {
        if (typeof card[method] !== 'function') {
          console.warn(`[${context}] Card缺少方法: ${method}`);
          return false;
        }
      }
      
      // 验证必需属性
      const requiredProperties = ['suit', 'rank', 'type', 'displayName', 'power'];
      for (const prop of requiredProperties) {
        if (!(prop in card)) {
          console.warn(`[${context}] Card缺少属性: ${prop}`);
          return false;
        }
      }
      
      return true;
    },

    /**
     * 安全的Card对象访问器
     */
    safeGetCardColor(card, fallback = '#666') {
      try {
        if (this.validateCardObject(card, 'safeGetCardColor')) {
          return card.getColor();
        }
        return fallback;
      } catch (error) {
        console.error('获取卡牌颜色失败:', error);
        return fallback;
      }
    },

    safeGetCardSymbol(card, fallback = '?') {
      try {
        if (this.validateCardObject(card, 'safeGetCardSymbol')) {
          return card.getSymbol();
        }
        return fallback;
      } catch (error) {
        console.error('获取卡牌符号失败:', error);
        return fallback;
      }
    },

    /**
     * Card重建错误处理
     */
    handleCardRebuildError(error, cardData, context = 'unknown') {
      const severity = this.classifyCardError(error);
      
      switch (severity) {
        case 'critical':
          // 严重错误：停止游戏，提示用户
          this.message = '卡牌数据异常，请重新开始游戏';
          this.messageType = 'error';
          console.error(`[${context}] 严重Card错误:`, error, cardData);
          break;
          
        case 'recoverable':
          // 可恢复错误：使用默认卡牌占位
          console.warn(`[${context}] 可恢复Card错误，使用降级方案:`, error, cardData);
          return this.createFallbackCard(cardData);
          
        case 'minor':
        default:
          // 轻微错误：记录日志继续
          console.log(`[${context}] 轻微Card错误:`, error, cardData);
          return this.createFallbackCard(cardData);
      }
    },

    /**
     * 分类Card错误严重程度
     */
    classifyCardError(error) {
      const errorMessage = error.message || error.toString();
      
      // 严重错误：数据完全无效
      if (errorMessage.includes('Invalid card JSON data') && !error.cardData) {
        return 'critical';
      }
      
      // 可恢复错误：缺少字段或方法
      if (errorMessage.includes('Missing required field') || 
          errorMessage.includes('missing getColor method') ||
          errorMessage.includes('missing getSymbol method')) {
        return 'recoverable';
      }
      
      // 默认为轻微错误
      return 'minor';
    },

    /**
     * 创建降级Card对象
     */
    createFallbackCard(originalData) {
      // 创建一个基本可用的Card对象
      try {
        return new Card(
          originalData?.suit || 'hearts',
          originalData?.rank || '7',
          originalData?.type || '卒',
          originalData?.displayName || '未知牌'
        );
      } catch (error) {
        // 最后的降级：返回最基本的对象
        return {
          suit: 'hearts',
          rank: '7',
          type: '卒',
          displayName: '占位牌',
          power: 1,
          getColor: () => '#666',
          getSymbol: () => '?',
          canPairWith: () => false
        };
      }
    }
  }
});
